<?
ini_set("display_errors",1);
include($_SERVER['DOCUMENT_ROOT'].'/includes/functions.inc.php');
include($_SERVER['DOCUMENT_ROOT'].'/config.php');
include($_SERVER['DOCUMENT_ROOT'].'/groups/database.php');
include($_SERVER['DOCUMENT_ROOT'].'/filter.libs.php');

portal_start();

####################################
#

include($_SERVER['DOCUMENT_ROOT'].'/header.inc.php');

if (empty($_GET)) {
	if ($portal['homepage_template'] !='') {
		
		include($_SERVER['DOCUMENT_ROOT'].'/homepage.php');
		
		include($_SERVER['DOCUMENT_ROOT'].'/footer.inc.php');
		exit;
	}
	if ($portal['count'] < 1000) {
		parse_str("view=thumbs&order=added&in=d&opt=byyear4",$_GET);
	}
	display_header();
}

setup_defaults();

customise();

include($_SERVER['DOCUMENT_ROOT']."/options/{$opt['opt']}.php");

include($_SERVER['DOCUMENT_ROOT'].'/common/mainstyleselect.inc.php');

setup_paging();

if (isset($_GET['a'])) {
	include($_SERVER['DOCUMENT_ROOT'].'/common/accordian.inc.php');
}

display_results(); //wrapper around /views/{$opt['view']}.php

include($_SERVER['DOCUMENT_ROOT'].'/footer.inc.php');

#
####################################






# FUNCTIONS:



#########################
#

function display_header() {
	global $portal;
	
	if (!empty($portal['description'])) {
		print "<div style=\"padding:5px;margin:5px;background-color:#eeeeee;font-size:1.1em\">".MakeLinks(he($portal['description']))."</div>";
	} elseif (!empty($portal['excerpt'])) {
		print "<p><b>".he($portal['excerpt'])."</b>";
	} else {
		print "<div style=\"padding:5px;margin:5px;background-color:#eeeeee;font-size:1.1em\">Welcome to the <b>".he($portal['title'])."</b> Portal!</div>";
	}
}


#########################
# Setup Defaults

function setup_defaults() {
	global $sql,$opt,$views,$orders,$options;
	global $portal_id,$portal;
	
	$sql = array();
	$sql['columns'] = 'gridimage_id,title,realname,user_id,grid_reference,comment';
	$sql['tables'] = array();

	$sql['tables'][] = "p2.gridimage{$portal_id}_bi_view AS gi";
	#$sql['tables'][] = "p2.gridimage{$portal_id}_bi AS gi";
	#$sql['tables'][] = "INNER JOIN geograph_live.gridimage_search AS gs USING (gridimage_id)";

	$sql['wheres'] = array();

	$sql['order'] = "created DESC,gridimage_id DESC";
	$sql['limit'] = 25;

	#########################

	$opt = array();
	$opt['view'] = 'thumbs';
	$opt['title'] = "images recently added to this portal...";
	$opt['order'] = 'added';
	$opt['in'] = 'd';
	$opt['opt'] = 'default';
	$opt['has_hidden'] = false;
	$opt['filtered'] = false;

	$views = array(
	'listing' => '&middot; Full Listing',
	'thumbs' => '&middot; Thumbnails',
	'thumbs2' => '&middot; Thumbnails2',
	'text' => '&middot; Plain-Text',
	'csv' => 'download as CSV',
	);

	$orders = array(
	'added' => 'Added',
	'taken' => 'Date taken',
	'gridref' => 'Grid Reference',
	'realname' => 'Contributor Name',
	'title' => 'Title',
	'category' => 'Category',
	'y' => 'South->North',
	'x' => 'West->East',
	'submitted' => 'Date submitted',
	);

	$options = array(
	'' => 'All',
	'byyear' => 'Broken by Year',
	'byyear4' => '4 per Year',
	'gridref' => '4 per Grid Reference',
	'myriad' => '4 per Myriad',
	'categories' => '4 per Category',
	'users' => '4 per Contributor',
	'shared' => '4 per Shared Descriptions',
	'cluster' => '4 per Automatic Cluster',
	'cluster2' => '4 per Automatic Cluster2'
	);
	if (getOne("SELECT COUNT(*) FROM p2.gridimage2tag{$portal_id}_bi") > 0) {
		$options['tags'] = "4 per Tag";
	}
	if ($portal['linear_start_id'] > 0) {
		$orders['linear'] = "Linear Order";
		$options['linear'] = "4 per Linear Group";
	}
}

#########################
# Customise

function customise() {
	global $sql,$opt,$views,$orders,$options;
	global $pgsize,$resultCount,$numberOfPages,$page,$pg;
	
	if (!empty($_GET['view'])) {

		if (isset($views[$_GET['view']])) {
			$opt['view'] = $_GET['view'];
		}
		if ($opt['view'] == 'csv') {
			$sql['columns'] .= ",wgs84_lat,wgs84_long";
		} elseif ($opt['view'] == 'listing') {
			$sql['columns'] .= ",imagetaken,imageclass";
		}
	} 

	if (!empty($_GET['order'])) {
		if (!empty($_GET['in']) && strlen($_GET['in']) == 1) $opt['in'] = $_GET['in'];
		$asc = ($opt['in'] == 'a')?'asc':'desc';
		switch ($_GET['order']) {
			case 'taken': $sql['order'] = "imagetaken $asc,gridimage_id $asc"; $opt['order']= 'taken'; break;
			case 'submitted': $sql['order'] = "gridimage_id $asc"; $opt['order']= 'submitted'; break;
			case 'gridref': $sql['order'] = "grid_reference $asc,gridimage_id $asc"; $opt['order']= 'gridref'; break;
			case 'realname': $sql['order'] = "realname $asc,gridimage_id $asc"; $opt['order']= 'realname'; break;
			case 'title': $sql['order'] = "title $asc,gridimage_id $asc"; $opt['order']= 'title'; break;
			case 'category': $sql['order'] = "imageclass $asc,gridimage_id $asc"; $opt['order']= 'category'; break;
			case 'y': $sql['order'] = "y $asc,gridimage_id $asc"; $opt['order']= 'y'; break;
			case 'x': $sql['order'] = "x $asc,gridimage_id $asc"; $opt['order']= 'x'; break;
			case 'linear': $sql['order'] = "custom_sort $asc,gridimage_id $asc"; $opt['order']= 'linear'; $sql['wheres'][] = "custom_sort > 0"; break;
			case 'added': 
			     default: $sql['order'] = "created $asc,gridimage_id $asc";  $opt['order']= 'added'; break;
		}
		$opt['title'] = '';
	}
	
	if (!empty($_GET['opt']) && preg_match('/^\w+$/',$_GET['opt'])) {
		$filename = $_SERVER['DOCUMENT_ROOT']."/options/{$_GET['opt']}.php";
		if (file_exists($filename)) {
			$opt['opt'] = $_GET['opt'];
		}
	}
}

#########################
# Paging...

function setup_paging() {
	global $sql,$opt;
	global $pgsize,$resultCount,$numberOfPages,$page,$pg;
	
	if (empty($pgsize)) {$pgsize = 25;}

			list($usec, $sec) = explode(' ',microtime());
			$querytime_before = ((float)$usec + (float)$sec);

	$count_query = sqlMakeCountQuery($sql);

			list($usec, $sec) = explode(' ',microtime());
			$querytime_after = ((float)$usec + (float)$sec);

			if (($querytime_after-$querytime_before) > 0.1) {
				$hh = fopen("./slow.log",'a');
				fprintf($hh,"%0.4f,COUNT,%d,%d,%s\n",$querytime_after-$querytime_before,$portal_id,time(),str_replace(array("\n","\r"),' ',$count_query));
				fclose($hh);
			}

	$resultCount = getOne($count_query);

	$numberOfPages = ceil($resultCount/$pgsize);

	if (!empty($_GET['page'])) {

		$page = intval($_GET['page']);

		if (empty($page) || $page < 1) {$page = 1;}
		if ($page > $numberOfPages) {$page = $numberOfPages;}

		$pg = ($page -1)* $pgsize;

		$sql['limit'] = "$pg,$pgsize";
	} else {
		$page = 1;
		$pg = 0;
	}

}

#########################
# Display results!

function display_results() {
	global $sql,$opt,$views,$orders,$options;
	global $pgsize,$resultCount,$numberOfPages,$page,$pg;
	global $c;
	
	if ($resultCount) {
		$query = sqlMakeQuery($sql);
		if (isset($_GET['ddd'])) {
			print_rp($sql);
			print $query;
		}
				list($usec, $sec) = explode(' ',microtime());
				$querytime_before = ((float)$usec + (float)$sec);

		$result = queryExecute($query);

				list($usec, $sec) = explode(' ',microtime());
				$querytime_after = ((float)$usec + (float)$sec);

				if (($querytime_after-$querytime_before) > 0.1) {
					$hh = fopen("./slow.log",'a');
					fprintf($hh,"%0.4f,MAINQ,%d,%d,%s\n",$querytime_after-$querytime_before,$portal_id,time(),str_replace(array("\n","\r"),' ',$query));
					fclose($hh);
				}

		if ($result) {
			print "<p style=clear:left>";
			if ($opt['title']) 
				print "<i>{$opt['title']}</i> ";
			if (!$opt['has_hidden']) {
				if ($resultCount > $pgsize) {
					printf("Photo %d..%d of %d. ",($pg)+1,min(($pg)+$pgsize,$resultCount),$resultCount);
				} else {
					print "$resultCount photos.";
				}
			}
			print "</p>";

			if ($numberOfPages > 1 && $page > 1) {
				print "<p class='pages'>".pagesString($page,$numberOfPages)."</p>";
			}

			include($_SERVER['DOCUMENT_ROOT']."/views/{$opt['view']}.php");

			if ($numberOfPages > 1) {
				print "<p class='pages'>Page $page of $numberOfPages. ";
				printf("Photo %d..%d of %d. ",($pg)+1,min(($pg)+$pgsize,$resultCount),$resultCount);
				print pagesString($page,$numberOfPages)."</p>";
			}

			if ($opt['filtered']) {
				print "<p>";
				if ($resultCount > 1) {
					print "<b>Further Links</b>: <a href=\"".linktoself(array(),"/breakdown.php")."\">View breakdown statistics for these images</a>";
				}
				
				if (!empty($_GET['cluster2'])) {
					print "<br/>Results too broad? <a href=\"/search.php?q=".urlencode($_GET['cluster2'])."\">View as Keyword Search</a>";
				}

				print "</p>";
			}
		} else {
			print "<p>Unable to Images to show at this time.</p>";
		}
	} else {
		$query = sqlMakeQuery($sql);
		if (isset($_GET['ddd'])) {
			print_rp($sql);
			print $query;
		}
		print "<p>No Images to show at this time.</p>";
	}
}


